package com.wutuo.roster.provider.constant;

import cn.apestar.cloud.provider.domain.Auth;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.GetPolicy;
import com.qiniu.api.rs.PutPolicy;
import com.qiniu.api.rs.URLUtils;
import org.apache.commons.codec.EncoderException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;

/**
 * 条形码和二维码编码解码
 *
 * @author ThinkGem
 * @version 2014-02-28
 */
public class ZxingHandler {

    /**
     * 条形码编码
     *
     * @param contents
     * @param width
     * @param height
     * @param imgPath
     */
    public static void encode(String contents, int width, int height, String imgPath) {
        int codeWidth = 3 + // start guard
            (7 * 6) + // left bars
            5 + // middle guard
            (7 * 6) + // right bars
            3; // end guard
        codeWidth = Math.max(codeWidth, width);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter()
                .encode(contents, BarcodeFormat.EAN_13, codeWidth, height, null);

            MatrixToImageWriter.writeToFile(bitMatrix, "png", new File(imgPath));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 条形码编码 - 七牛云
     *
     * @param contents
     * @param width
     * @param height
     * @param imgPath
     */
    public static String encodeQny(String contents, int width, int height, String imgPath) {
        width = 200; // 图像宽度
        height = 200; // 图像高度
        File file = new File(imgPath);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter()
                .encode(contents, BarcodeFormat.QR_CODE, width, height, null);
            MatrixToImageWriter.writeToFile(bitMatrix, "png", file);

            Mac mac = new Mac(Auth.QINIU_ACCESS_KEY, Auth.QINIU_SECRET_KEY);
            // 请确保该bucket已经存在
            PutPolicy putPolicy = new PutPolicy(Auth.QINIU_BUCKET_NAME);
            String uptoken = putPolicy.token(mac);
            PutExtra extra = new PutExtra();
            String key = System.currentTimeMillis() + file.getName();
            PutRet ret = IoApi.putFile(uptoken, key, file, extra);
            String url = getQiniuFileUrl(Auth.QINIU_DOMAIN, ret.getKey());
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载七牛云
     *
     * @return
     * @throws EncoderException
     * @throws AuthException
     */
    public static String getQiniuFileUrl(String demain, String key)
        throws EncoderException, AuthException {
        Mac mac = new Mac(Auth.QINIU_ACCESS_KEY, Auth.QINIU_SECRET_KEY);
        String baseUrl = URLUtils.makeBaseUrl(demain, key);
        GetPolicy getPolicy = new GetPolicy();
        String downloadUrl = getPolicy.makeRequest(baseUrl, mac);
        return downloadUrl;
    }

    /**
     * 条形码解码
     *
     * @param imgPath
     * @return String
     */
    public static String decode(String imgPath) {
        BufferedImage image = null;
        Result result = null;
        try {
            image = ImageIO.read(new File(imgPath));
            if (image == null) {
                System.out.println("the decode image may be not exit.");
            }
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

            result = new MultiFormatReader().decode(bitmap, null);
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 二维码编码
     *
     * @param contents
     * @param width
     * @param height
     * @param imgPath
     */
    public static void encode2(String contents, int width, int height, String imgPath) {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        // 指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        // 指定编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "GBK");
        try {
            BitMatrix bitMatrix = new MultiFormatWriter()
                .encode(contents, BarcodeFormat.QR_CODE, width, height, hints);

            MatrixToImageWriter.writeToFile(bitMatrix, "png", new File(imgPath));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 二维码解码
     *
     * @param imgPath
     * @return String
     */
    public static String decode2(String imgPath) {
        BufferedImage image = null;
        Result result = null;
        try {
            image = ImageIO.read(new File(imgPath));
            if (image == null) {
                System.out.println("the decode image may be not exit.");
            }
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

            Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
            hints.put(DecodeHintType.CHARACTER_SET, "GBK");

            result = new MultiFormatReader().decode(bitmap, hints);
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // /**
    // * @param args
    // */
    // public static void main(String[] args) {
    //
    // // 条形码
    // String imgPath = "F:\\image.png";
    // // String contents = "6923450657713";
    // // int width = 105, height = 50;
    // //
    // // ZxingHandler.encode(contents, width, height, imgPath);
    // // System.out.println("finished zxing EAN-13 encode.");
    // //
    // String decodeContent = ZxingHandler.decode(imgPath);
    // System.out.println("解码内容如下：" + decodeContent);
    // System.out.println("finished zxing EAN-13 decode.");
    //
    // // // 二维码
    // // String imgPath2 = "target\\zxing.png";
    // // String contents2 = "Hello Gem, welcome to Zxing!" + "\nBlog [
    // // http://thinkgem.iteye.com ]" + "\nEMail [ thinkgem@163.com ]";
    // // int width2 = 300, height2 = 300;
    // //
    // // ZxingHandler.encode2(contents2, width2, height2, imgPath2);
    // // System.out.println("finished zxing encode.");
    // //
    // // String decodeContent2 = ZxingHandler.decode2(imgPath2);
    // // System.out.println("解码内容如下：" + decodeContent2);
    // // System.out.println("finished zxing decode.");
    //
    // }

}